package com.hwj.service.Impl;

import com.hwj.entity.*;
import com.hwj.mapper.FollowMapper;
import com.hwj.mapper.NotifyMapper;
import com.hwj.service.FollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class FollowServiceImpl implements FollowService {
    @Autowired
    FollowMapper followMapper;
    @Autowired
    NotifyMapper notifyMapper;

    @Override
    public List<User> getFriends(Long userId) {
        return followMapper.getFriends(userId);
    }

    @Override
    public List<Post> listFriendsPosts(Long userId, Long friendId) {
        return followMapper.listFriendsPosts(userId,friendId);
    }

    @Override
    @Transactional
    public Boolean followFriend(Long loginId, Long userId) {
        List<Follow> follows = followMapper.listFollows();
        //是否存在这个关注
        follows = follows.stream()
                .filter(follow -> follow.getUserId().equals(loginId) && follow.getFollowedUserId().equals(userId))
                .collect(Collectors.toList());
        Boolean flag;
        if(follows.size()>0){
            flag=followMapper.deleteByPrimaryKey(follows.get(0).getFollowId())>0;
        }else {
            Follow follow=new Follow();
            follow.setFollowedUserId(userId);
            follow.setUserId(loginId);
            flag=followMapper.insertSelective(follow)>0;
            //插入通知
            Notify notify=new Notify();
            notify.setUserId(userId);
            notify.setContent("有人关注了你快去看看~");
            notifyMapper.insertSelective(notify);
        }
        return flag;
    }

    @Override
    public Boolean flagFollow(Long userId, Long followUserId) {
        return followMapper.listFollows().stream()
                .anyMatch(follow -> follow.getUserId().equals(userId) && follow.getFollowedUserId().equals(followUserId));
    }


}
